﻿using Furion.DependencyInjection;
using Furion.EventBus;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MyFurion.Start
{
    /// <summary>
    /// 全局异常处理
    /// </summary>
    public class ErrorLogFilter : IGlobalExceptionHandler, ISingleton
    {
        private readonly IEventPublisher _eventPublisher;
        /// <summary>
        /// 全局异常处理
        /// </summary>
        /// <param name="eventPublisher"></param>
        public ErrorLogFilter(IEventPublisher eventPublisher)
        {
            _eventPublisher = eventPublisher;
        }
        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            await _eventPublisher.PublishAsync(new ChannelEventSource("Add:ErrorLog",
                new ErrorLog
                {
                    ClassName = context.Exception.TargetSite?.DeclaringType?.FullName,
                    MethodName = context.Exception.TargetSite?.Name ?? String.Empty,
                    ExceptionName = context.Exception.Message,
                    ExceptionMsg = context.Exception.Message,
                    ExceptionSource = context.Exception.Source,
                    StackTrace = context.Exception.StackTrace,
                    ParamsObj = context.Exception.TargetSite?.GetParameters().ToString()
                }));
        }
    }
}
